#import <Foundation/Foundation.h>
#import <objc/runtime.h>

#import "FWCommon.h"


static CGSize const kScreenSizeiPhone = CGSizeMake(320, 480);
static CGSize const kScreenSizeiPad = CGSizeMake(768, 1024);


CGSize FWGetCurrentScreenSize()
{
    BOOL iPad = (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPhone);
    CGSize size = iPad ? kScreenSizeiPad : kScreenSizeiPhone;
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if ((orientation == UIInterfaceOrientationLandscapeLeft) || (orientation == UIInterfaceOrientationLandscapeRight)) {
        CGFloat tmp = size.height;
        size.height = size.width;
        size.width = tmp;
    }
    
    DebugLog(@"LI:FWTodo: Current screen size = {%f, %f}", size.width, size.height);

    return size;
}

BOOL FWIsDeviceAnIPad()
{
    return (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPhone);
}

NSString* FWBase64EncodeString(NSString* src) 
{
    static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    
    NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
    int length = [src length];
    
    for (int i = 0; i < length; i += 3) {
        for (int nib = 0; nib < 4; nib++) {
            // nibble:nib from char:byt
            int byt = (nib == 0) ? 0 : nib-1;
            int ix = (nib+1) * 2;
            
            if (i+byt >= length)
                break;
            
            // extract the top bits of the nibble, if valid
            unsigned char curr = (([src characterAtIndex:i+byt] << (8-ix)) & 0x3F);
            
            // extract the bottom bits of the nibble, if valid
            if (i+nib < length)
                curr |= (([src characterAtIndex:i+nib] >> ix) & 0x3F);
                
                [dest appendFormat:@"%c", base64[curr]];
        }
    }
    
    if ((length % 3) == 1)
        [dest appendString:@"=="];
    else if ((length % 3) == 2)
        [dest appendString:@"="];
    
    return dest;
}

NSString* FWXMLEncodeString(NSString *src)
{
    NSMutableString* str = [NSMutableString stringWithString:src];
    
    [str replaceOccurrencesOfString:@"&" withString:@"&amp;" options:NSLiteralSearch range:NSMakeRange(0, [str length])];
    [str replaceOccurrencesOfString:@"<" withString:@"&lt;" options:NSLiteralSearch range:NSMakeRange(0, [str length])];
    [str replaceOccurrencesOfString:@">" withString:@"&gt;" options:NSLiteralSearch range:NSMakeRange(0, [str length])];
    [str replaceOccurrencesOfString:@"'" withString:@"&apos;" options:NSLiteralSearch range:NSMakeRange(0, [str length])];
    [str replaceOccurrencesOfString:@"\"" withString:@"&quot;" options:NSLiteralSearch range:NSMakeRange(0, [str length])];
    
    return str;
}
